<template>
  <div class="item-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <item-search
        ref="searchFormRef"
        @search="handleSearch"
        @reset="handleReset"
      />

      <!-- 商品列表表格 -->
      <div class="table-container">
        <el-table
          :data="itemList"
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无数据"
          height="100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="商品图片" width="100">
            <template #default="scope">
              <el-image
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              ¥{{ (scope.row.price / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="category" label="类目" width="120" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column prop="spec" label="规格" width="120" />
          <el-table-column prop="sold" label="销量" width="100" />
          <el-table-column prop="commentCount" label="评论数" width="100" />
          <el-table-column prop="isAD" label="是否广告" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isAD ? 'success' : 'info'">
                {{ scope.row.isAD ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(scope.row.id)"
              >删除</el-button>
              <el-button
                v-if="scope.row.status === 1"
                type="warning"
                link
                @click="handleUpdateStatus(scope.row.id, 2)"
              >下架</el-button>
              <el-button
                v-if="scope.row.status === 2"
                type="success"
                link
                @click="handleUpdateStatus(scope.row.id, 1)"
              >上架</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          :total="total"
          :page-count="Math.ceil(total / queryParams.pageSize)"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品表单对话框 -->
    <item-form
      v-model:visible="formDialogVisible"
      :title="formTitle"
      :item-data="currentItem"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ItemDTO, ItemPageQuery } from '@/api/item'
import { getItemList, deleteItem, updateItemStatus, createItem, updateItem } from '@/api/item'
import ItemForm from './components/ItemForm.vue'
import ItemSearch from './components/ItemSearch.vue'

const itemList = ref<ItemDTO[]>([])
const loading = ref(false)
const formDialogVisible = ref(false)
const formTitle = ref('新增商品')
const currentItem = ref<ItemDTO>()
const total = ref(0)

// 查询参数
const queryParams = reactive<ItemPageQuery>({
  pageNo: 1,
  pageSize: 10,
  key: '',
  brand: '',
  category: '',
  minPrice: undefined,
  maxPrice: undefined
})

// 查询按钮点击
const searchFormRef = ref()
const handleSearch = (params: ItemPageQuery) => {
  queryParams.pageNo = 1
  // 保持价格单位为分，不需要再次转换
  Object.assign(queryParams, params)
  getList()
}

// 重置查询
const handleReset = () => {
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  queryParams.key = ''
  queryParams.brand = ''
  queryParams.category = ''
  queryParams.minPrice = undefined
  queryParams.maxPrice = undefined
  getList()
}

// 滚动加载
const handleScroll = ({ scrollTop, scrollHeight, clientHeight }: { scrollTop: number; scrollHeight: number; clientHeight: number }) => {
  // 当滚动到底部时加载更多数据
  if (scrollHeight - scrollTop - clientHeight < 50 && !loading.value && itemList.value.length < total.value) {
    queryParams.pageNo++
    loadMore()
  }
}

// 加载更多数据
const loadMore = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const response = await getItemList(queryParams)
    itemList.value = [...itemList.value, ...response.data.list]
  } catch (error) {
    console.error('加载更多数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取商品列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getItemList({
      ...queryParams,
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize
    })
    itemList.value = response.data.list
    total.value = Number(response.data.total)
  } catch (error) {
    console.error('获取商品列表失败:', error)
    itemList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 每页条数改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  queryParams.pageNo = 1
  getList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

// 删除商品
const handleDelete = async (id: number | undefined) => {
  if (!id) return
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await deleteItem(id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 更新商品状态
const handleUpdateStatus = async (id: number | undefined, status: number) => {
  if (!id) return
  try {
    await updateItemStatus(id, status)
    ElMessage.success('操作成功')
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 新增商品
const handleAdd = () => {
  formTitle.value = '新增商品'
  currentItem.value = undefined
  formDialogVisible.value = true
}

// 编辑商品
const handleEdit = (item: ItemDTO) => {
  formTitle.value = '编辑商品'
  currentItem.value = { ...item }
  formDialogVisible.value = true
}

// 表单提交成功
const handleFormSuccess = async (formData: ItemDTO) => {
  try {
    if (formData.id) {
      // 更新商品
      await updateItem(formData)
      ElMessage.success('更新成功')
    } else {
      // 新增商品
      await createItem(formData)
      ElMessage.success('新增成功')
    }
    formDialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '正常'
    case 2:
      return '下架'
    case 3:
      return '删除'
    default:
      return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.item-container {
  padding: 20px;
  height: calc(100vh - 120px);
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: auto;
  padding: 20px 0;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;
}
</style>
